package com.leizhou.consumer.controller;

import com.leizhou.consumer.pojo.User;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @author LT
 * @version 1.0.0
 * @ClassName ConsumerController.java
 * @Description TODO
 * @createTime 2020年04月24日 16:11:00
 */
@RestController
@RequestMapping("/consumer")
@Slf4j
@DefaultProperties(defaultFallback = "defaultFallback")
public class ConsumerController {

    // 注入发现者
    @Autowired
    private DiscoveryClient discoveryClient;
    @Autowired
    private RestTemplate restTemplate;

    /**
     * 根据主键id查询用户
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    // @HystrixCommand  // 默认 requestVolumeThreshold = 20秒
    @HystrixCommand(commandProperties = {
            @HystrixProperty(name="circuitBreaker.requestVolumeThreshold",value="5"),
            @HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds",value="20000"),
            @HystrixProperty(name="circuitBreaker.errorThresholdPercentage",value="50")
    })
    public String findOne(@PathVariable("id") Long id) {
        if (id == 1) {
            throw new RuntimeException("太忙了");
        }

        // // 根据服务id，获取该服务的全部实例
        // List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
        //
        // // 获取第一个服务实例(因为目前我们只有一个服务实例)
        // ServiceInstance serviceInstance = instances.get(0);
        //
        // // 获取服务实例所在的主机
        // String host = serviceInstance.getHost();
        //
        // // 获取服务实例所在的端口
        // int port = serviceInstance.getPort();

        // 定义服务实例来访问url
        // String url = "http://" + host + ":" + port + "/user/" + id;
        // System.out.println("服务实例访问的url地址 = " + url);
        String url = "http://user-service/user/" + id;
        System.out.println("url = " + url);
        return restTemplate.getForObject(url, String.class);
    }

    public String findOneFallback(Long id) {
        log.error("查询用户信息失败。id:{}", id);
        return "对不起，网络拥挤请稍等！";
    }

    public String defaultFallback() {
        return "默认提示：对不起，网络拥挤请稍等";
    }
}
